package initialize

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"goods_srv/global"
)

func InitRegisterConsul() {
	config := api.DefaultConfig()
	//连接consul的地址：127.0.0.1:8500
	config.Address = fmt.Sprintf("%s:%d", global.AppConf.ConsulConfig.ConsulHost, global.AppConf.ConsulConfig.ConsulPort)
	//实例化consul客户端
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Panic(err)
	}
	//生成健康检测的检查对象

	check := &api.AgentServiceCheck{
		Interval:                       "5s", //健康检查间隔
		Timeout:                        "5s",
		GRPC:                           fmt.Sprintf("%s:%d", global.AppConf.Ip, global.AppConf.Port), //公网地址和获取的空闲端口号
		DeregisterCriticalServiceAfter: "1s",
	}

	registration := api.AgentServiceRegistration{
		ID:      global.ServerId,                  //uuid生成的随机字符串
		Name:    global.AppConf.Name,              //服务名称
		Tags:    global.AppConf.ConsulConfig.Tags, //标签
		Port:    global.AppConf.Port,              //随机的端口号
		Address: global.AppConf.Ip,                // 公网地址
		Check:   check,
	}
	err = client.Agent().ServiceRegister(&registration)
	if err != nil {
		zap.S().Panic(err)
	}
}
